﻿///<reference path="../../jquery-1.3.2-vsdoc.js" />
///<reference path="../Shell/Base.js" />
(function($, epi) {
    epi = epi || {};
    epi.dashboard = epi.dashboard || {};
    epi.dashboard.manager = epi.dashboard.manager || {};

    epi.dashboard.manager.gadget = function() {
        var pub = {};

        //EPiServerShellResourcesShared
        var _sharedResourceKey = "EPiServer.Shell.Resources.Texts";
        var _dashboardResourceKey = "EPiServer.Shell.UI.Views.Dashboard.Resources";

        pub.init = function() {
         /*   $(document).bind("epigadgetremove", _gadgetRemoveCommand)
                   .bind("epigadgetrestore", _gadgetRestoreCommand)
                   .bind("epigadgetmove", _gadgetMoveCommand);

            if (typeof pub.move !== "undefined") {
                $(document).bind("epigadgetinitmove", pub.move.init);
            }*/
        };

        var _createMoveGadgetData = function(gadget) {
            /// <summary>
            ///     Creates the JSON object with data to where the gadget is moved.
            /// </summary>
            /// <param name="gadget" type="jQuery Element">
            ///      Gadget element representing the moved gadget. JQuery element.
            /// </param>
            var gadgetID = gadget.get(0).getAttribute("id").replace(/^gadget_/, "");
            var gadgetContainer = gadget.parent("div.epi-gadgetContainer");
            var containerID = gadgetContainer.get(0).getAttribute("id").replace(/^gadgetContainer_/, "");
            var gadgetPosition = gadget.prevAll(":visible").length;

            return { gadgetID: gadgetID, containerID: containerID, indexPosition: gadgetPosition };
        };

        var _gadgetRemoveCommand = function(e) {
            /// <summary>
            ///     Sends the request to the server to update the data with the remove.
            /// </summary>
            /// <param name="id" type="String">
            ///     The string representation of the GUID that identifies the gadget.
            /// </param>
            if (!confirm(epi.shell.resource.get(_dashboardResourceKey, "ConfirmDeleteGadget"))) {
                return false;
            }

            var gadget = $(e.target);
            var gadgetId = gadget.attr("id").replace(/gadget_/, "");

            var errorHandler = function(xmlHttpRequest, status, errorThrown) {
                epi.dashboard.manager.feedback.epiFeedback("setErrorMessage", epi.shell.resource.get(_dashboardResourceKey, "ErrorDeleteGadget"), xmlHttpRequest.responseText);
            };

            var successHandler = function(data) {
                var feedback = $("#feedback");
                epi.dashboard.manager.feedback.epiFeedback("setMessage", epi.shell.resource.get(_dashboardResourceKey, "GadgetRemovedMessage"),
                    {
                        UndoButton: {
                            text: epi.shell.resource.get(_sharedResourceKey, "Undo"),
                            description: epi.shell.resource.get(_dashboardResourceKey, "GadgetRemovedUndoDescription"),
                            click: function(e) {
                                $('#dashboardTabs').trigger('epigadgetrestore', gadgetId);
                            },
                            tabIndex: 0
                        }
                    });

                epi.dashboard.manager.feedback.epiFeedback("transferToFeedback", gadget);
                gadget.epiGadget("triggerUnload");
                gadget.hide();
                // TODO: Implement total remove of gadget when Add gadget is implemented
                //                gadget.remove();
                //                gadget.destroy();
            };

            epi.shell.addToAjaxQueue({
                url: epi.shell.routes.getActionPath({ controller: 'Dashboard', action: 'RemoveGadget' }),
                type: "POST",
                dataType: "json",
                data: { gadgetId: gadgetId },
                error: errorHandler,
                success: successHandler
            });

        };

        var _gadgetRestoreCommand = function(e, gadgetId) {
            /// <summary>
            ///     Sends the request to the server to update the data with the restore.
            /// </summary>
            /// <param name="id" type="String">
            ///     The string representation of the GUID that identifies the gadget.
            /// </param>

            var errorHandler = function(xmlHttpRequest, status, errorThrown) {
                epi.dashboard.manager.feedback.epiFeedback("setErrorMessage", epi.shell.resource.get(_dashboardResourceKey, "ErrorRestoreGadget"), xmlHttpRequest.responseText);
            };

            var successHandler = function(data) {
                var gadget = $("#gadget_" + gadgetId);
                gadget.show();
                epi.dashboard.manager.feedback.epiFeedback("transferFromFeedback", "#gadget_" + gadgetId, function() { epi.dashboard.manager.feedback.epiFeedback("hide"); });
                gadget.trigger("epigadgetloaded", gadget.epiGadget("getInstance"));

            };

            epi.shell.addToAjaxQueue({
                url: epi.shell.routes.getActionPath({ controller: 'Dashboard', action: 'RestoreGadget' }),
                type: "POST",
                dataType: "json",
                data: { gadgetId: gadgetId },
                error: errorHandler,
                success: successHandler
            }, { keepFeedback: true });
        };

        var _gadgetMoveCommand = function(e) {
            /// <summary>
            ///     Saves the ordering of gadgets after one gadget is moved.
            /// </summary>
            var data = _createMoveGadgetData($(e.target));

            var errorHandler = function(xmlHttpRequest, status, errorThrown) {
                epi.dashboard.manager.feedback.epiFeedback("setErrorMessage", epi.shell.resource.get(_dashboardResourceKey, "ErrorMoveGadget"), xmlHttpRequest.responseText);
            };

            var successHandler = function(data) {
                // move done
            };

            epi.shell.addToAjaxQueue({
                url: epi.shell.routes.getActionPath({ controller: 'Dashboard', action: 'MoveGadget' }),
                type: "POST",
                dataType: "json",
                data: data,
                error: errorHandler,
                success: successHandler
            });
        };
        
        return pub;
    } ();

})(epiJQuery, epi);